﻿//
// (C) Copyright 2009 Irantha Suwandarathna (iranthas@hotmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EffiProz.Core.Lib;
using EffiProz.Core.DataTypes;
using EffiProz.Core.Indexes;
using EffiProz.Core.Errors;
using EffiProz.Core.Persist;
using EffiProz.Core.Results;
using EffiProz.Core.Navigators;

namespace EffiProz.Core
{
    public class StatementInsert : StatementDML
    {
        /**
     * Instantiate this as an INSERT_VALUES statement.
     */
        public StatementInsert(Session session, Table targetTable, int[] columnMap,
                         Expression insertExpression, bool[] checkColumns,
                         ParserDML.CompileContext compileContext)
            : base(StatementTypes.INSERT, StatementTypes.X_SQL_DATA_CHANGE,
                session.getCurrentSchemaHsqlName())
        {



            this.targetTable = targetTable;
            this.baseTable = targetTable.getBaseTable();
            this.insertColumnMap = columnMap;
            this.insertCheckColumns = checkColumns;
            this.insertExpression = insertExpression;
            this._isTransactionStatement = true;

            setDatabseObjects(compileContext);
            checkAccessRights(session);
        }

        /**
         * Instantiate this as an INSERT_SELECT statement.
         */
        public StatementInsert(Session session, Table targetTable, int[] columnMap,
                        bool[] checkColumns, QueryExpression queryExpression,
                        ParserDML.CompileContext compileContext)
            : base(StatementTypes.INSERT, StatementTypes.X_SQL_DATA_CHANGE,
                session.getCurrentSchemaHsqlName())
        {



            this.targetTable = targetTable;
            this.baseTable = targetTable.getBaseTable();
            this.insertColumnMap = columnMap;
            this.insertCheckColumns = checkColumns;
            this.queryExpression = queryExpression;
            this._isTransactionStatement = true;

            setDatabseObjects(compileContext);
            checkAccessRights(session);
        }

        /**
         * Executes an INSERT_SELECT or INSERT_VALUESstatement.  It is assumed that the argument
         * is of the correct type.
         *
         * @return the result of executing the statement
         */
        public override Result getResult(Session session)
        {

            Table table = baseTable;
            Result resultOut = null;
            RowSetNavigator generatedNavigator = null;
            PersistentStore store = session.sessionData.getRowStore(baseTable);

            if (generatedIndexes != null)
            {
                resultOut = Result.newUpdateCountResult(_generatedResultMetaData,
                        0);
                generatedNavigator = resultOut.getChainedResult().getNavigator();
            }

            RowSetNavigator newDataNavigator = queryExpression == null
                                               ? getInsertValuesNavigator(session)
                                               : getInsertSelectNavigator(session);
            Expression checkCondition = null;
            RangeVariable.RangeIteratorBase checkIterator = null;

            if (targetTable != baseTable)
            {
                QuerySpecification select =
                    ((TableDerived)targetTable).getQueryExpression()
                        .getMainSelect();

                checkCondition = select.checkQueryCondition;

                if (checkCondition != null)
                {
                    checkIterator = select.rangeVariables[0].getIterator(session);
                }
            }

            while (newDataNavigator.hasNext())
            {
                Object[] data = newDataNavigator.getNext();

                if (checkCondition != null)
                {
                    checkIterator.currentData = data;

                    bool check = checkCondition.testCondition(session);

                    if (!check)
                    {
                        throw Error.error(ErrorCode.X_44000);
                    }
                }

                table.insertRow(session, store, data);

                if (generatedNavigator != null)
                {
                    Object[] generatedValues = getGeneratedColumns(data);

                    generatedNavigator.add(generatedValues);
                }
            }

            newDataNavigator.beforeFirst();
            table.fireTriggers(session, TriggerConstants.INSERT_AFTER, newDataNavigator);

            if (resultOut == null)
            {
                resultOut =
                    Result.getUpdateCountResult(newDataNavigator.getSize());
            }
            else
            {
                resultOut.setUpdateCount(newDataNavigator.getSize());
            }

            return resultOut;
        }

        public RowSetNavigator getInsertSelectNavigator(Session session)
        {

            SqlType[] colTypes = baseTable.getColumnTypes();
            int[] columnMap = insertColumnMap;

            //
            Result result = queryExpression.getResult(session, 0);
            RowSetNavigator nav = result.initialiseNavigator();
            SqlType[] sourceTypes = result.metaData.columnTypes;
            RowSetNavigatorClient newData = new RowSetNavigatorClient(2);

            while (nav.hasNext())
            {
                Object[] data = baseTable.getNewRowData(session);
                Object[] sourceData = (Object[])nav.getNext();

                for (int i = 0; i < columnMap.Length; i++)
                {
                    int j = columnMap[i];
                    SqlType sourceType = sourceTypes[i];

                    data[j] = colTypes[j].convertToType(session, sourceData[i],
                                                        sourceType);
                }

                newData.add(data);
            }

            return newData;
        }

        public RowSetNavigator getInsertValuesNavigator(Session session)
        {

            SqlType[] colTypes = baseTable.getColumnTypes();
            int[] columnMap = insertColumnMap;

            //
            Expression[] list = insertExpression.nodes;
            RowSetNavigatorClient newData = new RowSetNavigatorClient(list.Length);

            for (int j = 0; j < list.Length; j++)
            {
                Expression[] rowArgs = list[j].nodes;
                Object[] data = baseTable.getNewRowData(session);

                session.sessionData.startRowProcessing();

                for (int i = 0; i < rowArgs.Length; i++)
                {
                    Expression e = rowArgs[i];
                    int colIndex = columnMap[i];

                    if (e.getType() == OpTypes.DEFAULT)
                    {
                        if (baseTable.identityColumn == colIndex)
                        {
                            continue;
                        }

                        if (baseTable.colDefaults[colIndex] != null)
                        {
                            data[colIndex] =
                                baseTable.colDefaults[colIndex].getValue(session);

                            continue;
                        }

                        continue;
                    }

                    data[colIndex] = colTypes[colIndex].convertToType(session,
                            e.getValue(session), e.getDataType());
                }

                newData.add(data);
            }

            return newData;
        }
    }
}
